//
//  CZNormalViewController.swift
//  GZWeibo007
//
//  Created by 易辉华 on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZNormalViewController:UIViewController,UITableViewDataSource,UITableViewDelegate,CZStatusBottomViewDelegate,CZStatusCellDelegate,CZDetailHeaderViewDelegate {
    
    ///MARK: - 属性
    ///微博模型
    private var status: CZStatus
    
    
    //评论模型
    private var comments: [CZDetailCommentModel] = [CZDetailCommentModel]()
    
    init(status: CZStatus) {
        self.status = status
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        
        self.title = "微博详情"
        view.backgroundColor = UIColor.lightGrayColor()
        
        //        self.tabBarController?.tabBar.hidden = true
        
        //tableView的代理
        tableView.delegate = self
        tableView.dataSource = self
        //        tableView.estimatedRowHeight = 200
        
        //准备UI
        prepareUI()
    }
    
    
    
    func prepareUI() {
        
        //添加子控件
        view.addSubview(bottomView)
        view.addSubview(tableView)
        
        tableView.estimatedRowHeight = 300
        //添加约束
        tableView.ff_Fill(view, insets: UIEdgeInsets(top: 60, left: 0, bottom: 44, right: 0))
        bottomView.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44), offset: CGPoint(x: 0, y: 0))
        
        //注册cell
        
        //普通cell
        
        //注册Cell
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier:CZStatusDetailIdentifier.DetailStatusNormalCell.rawValue)
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier:CZStatusDetailIdentifier.DetailStatusForwardCell.rawValue)
        tableView.registerClass(CZCommentCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailCommentCell.rawValue)
        
        tableView.registerClass(CZDetailLoadingCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailLoadingCell.rawValue)
        
        tableView.registerClass(CZDetailNoDataCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailNoDataCell.rawValue)
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        // 添加上拉加载更多控件
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            // 加载更多数据
            print("加载更多评论")
            self.loadMoreComment()
        }
        tableView.tableFooterView = UIView()
    }
    
    
    ///代理方法
    // MARK: - tableView头部代理
    func detailHeaderViewClick(headerView: UIView) {
        // 加载 `最新评论`
        print("加载评论")
        loadNewComment()
    }
    
    // MARK: - 加载最新评论
    /// 加载最新评论
    private func loadNewComment() {
        let since_id = comments.first?.id ?? 0
        
        // 添加 正在加载数据的cell
        let loadCommentModel = CZDetailCommentModel(loading: true)
        comments.insert(loadCommentModel, atIndex: 0)
        
        // 重新刷新数据
        tableView.reloadData()
        
        // 滚动到第1组第0个cell
        tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
        
        CZDetailCommentModel.loadComment(status.id, since_id: since_id, max_id: 0) { (comments, total_number, previous_cursor, next_cursor, error) -> () in
            
            // 移除正在加载数据的cell
            self.comments.removeFirst()
            
            if error != nil {
                print("加载最新评论失败: \(error)")
                SVProgressHUD.showErrorWithStatus("加载最新评论失败")
                // 重新刷新数据
                self.tableView.reloadData()
                return
            }
            
            print("加载最新评论成功:\(comments?.count), next_cursor: \(next_cursor)")
            self.status.comments_count = total_number!
            
            //            SVProgressHUD.showInfoWithStatus("加载 \(comments?.count ?? 0) 条最新评论")
            
            // 判断是否加载到数据
            if comments != nil && comments?.count > 0 {
                
                // 将新获取到的数据拼接在现有数据的前面
                self.comments = comments! + self.comments
            }
            
            // 重新刷新数据
            self.tableView.reloadData()
        }
    }
    
    // MARK: - 加载更多评论
    /// 加载更多评论
    private func loadMoreComment() {
        CZDetailCommentModel.loadComment(status.id, since_id: 0, max_id: comments.last?.id ?? 0) { (comments, total_number, previous_cursor, next_cursor, error) -> () in
            // 停止上拉加载更多数据动画
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                SVProgressHUD.showErrorWithStatus("加载更多评论失败")
                print("加载更多评论失败: \(error)")
                return
            }
            
            print("加载更多评论成功:\(comments?.count), next_cursor: \(next_cursor)")
            self.status.comments_count = total_number!
            
            //            SVProgressHUD.showInfoWithStatus("加载 \(comments?.count ?? 0) 条更多评论")
            
            self.tableView.showsInfiniteScrolling = next_cursor != 0
            
            // 判断是否加载到数据
            if comments != nil && comments?.count > 0 {
                // 将新获取到的数据拼接在现有数据的后面
                self.comments = self.comments + comments!
                
                // 重新刷新数据
                self.tableView.reloadData()
            }
            
        }
    }
    
    
    ///数据源和代理方法
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    //每组多少行
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return 1
        }else{
            if comments.count == 0{
                
                return comments.count
            }else{
                
                return comments.count
                
            }
            
        }
        
    }
    
    //cell行高
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            
            let cellId = CZStatusDetailIdentifier.cellId(status)
            let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZStatusCell
            return cell.rowHeight(status)
        }else {
            
            if comments.count == 0 {
                
                return 200
            }else{
                
                return UITableViewAutomaticDimension
            }
            
        }
    }
    
    //设置cell头部高度
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0{
            
            return 0
        }else{
            
            return 50
        }
        
    }
    
    //设置cell
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            
            let cellId = CZStatusDetailIdentifier.cellId(status)
            
            let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZStatusCell
            
            
            cell.cellDelegate = self
            cell.status = status
            
            return cell
        } else {
            
            if comments.count == 0 {
                let cell = tableView.dequeueReusableCellWithIdentifier(CZStatusDetailIdentifier.DetailNoDataCell.rawValue) as! CZDetailNoDataCell
                cell.message = "还没有人评论"
                return cell
            } else {
                let commentModel = comments[indexPath.row]
                
                let cellId = CZStatusDetailIdentifier.cellId(commentModel)
                
                let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZCommentCell
                
                cell.model = commentModel
                
                return cell
            }
        }
        
    }
    
    //cell头部的view
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if section == 1 {   // 第一组显示头部控件
            detailHeaderView.status = self.status
            return detailHeaderView
        } else {    // 其他组没有头部控件
            return nil
        }
    }
    
    
    //代理方法的实现

    func ZFBtnClick() {
        let zf = CZZFViewController(status: status)
        zf.hidesBottomBarWhenPushed = true
        //        navigationController?.pushViewController(zf, animated: true)
        presentViewController(UINavigationController(rootViewController: zf), animated: true, completion: nil)
    }
    func PLBtnClick() {
        let pl = CZPLViewController(status: status)
        pl.hidesBottomBarWhenPushed = true
        //        navigationController?.pushViewController(pl, animated: true)
        presentViewController(UINavigationController(rootViewController: pl), animated: true, completion: nil)
    }
    
    //TODO: - statusCell代理方法
    
    func forwardClick(status: CZStatus){
        print("原创微博")
        //TODO: 跳转到转发微博
        let forword_statuse = CZForwordController(status: status)
        
        navigationController?.pushViewController(forword_statuse, animated: true)
    }
    
    
    //MARK: - 懒加载
    
    private lazy var tableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.Plain)
    
    //显示没有评论的label
    private lazy var commentLabel:UILabel = {
        
        let label = UILabel()
        
        label.text = "没有评论"
        label.textColor = UIColor.lightGrayColor()
        label.font = UIFont.systemFontOfSize(15)
        label.sizeToFit()
        return label
    }()
    
    //    //头部点击的按钮
    //    private var commentButton:UIButton = {
    //        let commentButton = UIButton()
    //        commentButton.setTitle("评论", forState: UIControlState.Normal)
    //        commentButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
    //        commentButton.titleLabel?.font = UIFont.systemFontOfSize(12)
    //        return commentButton
    //    }()
    
    //第二组的头部
    
    ///headView
    private lazy var detailHeaderView: CZDetailHeaderView = {
        
        let view = CZDetailHeaderView()
        view.delegate = self
        
        view.status = self.status
        
        return view
    }()
    
    //    private var heardView:UIView = {
    //        let heardView = UIView()
    //        heardView.backgroundColor = UIColor(white: 0.99, alpha: 1)
    //        return heardView
    //    }()
    //
    //底部的view
    lazy var bottomView:CZStatusBottomView = {
        
        let bottomView = CZStatusBottomView()
        bottomView.delegate = self
        //        button.backgroundColor = UIColor.greenColor()
        return bottomView
        
    }()
    
}
